package beusoft.ccjk.com.apt;

import com.google.auto.service.AutoService;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

import beusoft.ccjk.com.apt.handler.AnnotationHandler;
import beusoft.ccjk.com.apt.handler.ViewInjectHandler;
import beusoft.ccjk.com.apt.util.LogUtil;
import beusoft.ccjk.com.apt.writer.AdapterWriter;
import beusoft.ccjk.com.apt.writer.DefaultJavaFileWriter;

/**
 * Created by CCJK on 2018/11/24.
 */
@SupportedAnnotationTypes("beusoft.ccjk.com.apt_anno.anno.*")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@AutoService(Processor.class)
public class MyProcessor extends AbstractProcessor {

    private List<AnnotationHandler> mHandlers = new LinkedList<>();
    final Map<String, List<Element>> map = new HashMap<>();
    AdapterWriter mWriter;

    public synchronized void init(ProcessingEnvironment env) {
        super.init(env);
        registerHandlers();
        mWriter = new DefaultJavaFileWriter(processingEnv);

    }

    private void registerHandlers() {
//        mHandlers.add(new MyHandler());
        mHandlers.add(new ViewInjectHandler());
    }

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        LogUtil.note(processingEnv, "开始注解编译");
        for (AnnotationHandler handler : mHandlers) {
            handler.attachProcessingEnv(processingEnv);
            map.putAll(handler.handleAnnotation(roundEnvironment));
        }
        mWriter.generate(map);
        LogUtil.note(processingEnv, "完成注解编译");
        return true;
    }


    @Override
    public SourceVersion getSupportedSourceVersion() {
        return SourceVersion.latestSupported();
    }


}
